<template>
    <div class="student-page">
        <el-card class="box-card">

            <!-- 搜索与筛选条件 -->
            <el-form :model="searchForm"
                label-width="70px"
                class="search-form">
                <el-row :gutter="20">
                    <el-col :span="5">
                        <el-form-item label="学生姓名">
                            <el-input v-model="searchForm.studentName"
                                placeholder="请输入"
                                size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="学生ID">
                            <el-input v-model="searchForm.studentId"
                                placeholder="请输入"
                                size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="班级">
                            <el-select v-model="searchForm.classsId"
                                placeholder="请选择"
                                filterable
                                :remote-method="remoteSearchClass"
                                :loading="classLoading"
                                remote
                                clearable
                                size="small">
                                <el-option label="全部"
                                    value="" />
                                <el-option v-for="item in filteredClasses"
                                    :key="item.classsId"
                                    :label="item.classsName"
                                    :value="item.classsId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item>
                            <el-button type="primary"
                                @click="handleSearch"
                                size="small">搜索</el-button>
                            <el-button @click="handleReset"
                                size="small">重置</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4" class="right-align-col">
                        <el-button type="primary"
                        @click="openAddDialog"
                        size="small">添加学生</el-button>
                    </el-col>
                </el-row>
            </el-form>

            <!-- 学生列表 -->
            <el-table :data="studentList"
                stripe
                style="width: 100%"
                v-loading="loading || classLoading"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection"
                    width="50" />
                <el-table-column prop="studentId"
                    label="学生ID"
                    width="120" />
                <el-table-column prop="studentName"
                    label="学生姓名"
                    width="100" />
                <el-table-column prop="gender"
                    label="性别"
                    width="80">
                    <template #default="scope">
                        {{ formatGender(scope.row.gender) }}
                    </template>
                </el-table-column>
                <el-table-column prop="studentPhone"
                    label="联系电话"
                    width="150" />
                <el-table-column prop="classsId"
                    label="班级">
                    <template #default="scope">
                        <span v-if="!isClassDataLoaded">加载中...</span>
                        <span v-else-if="!scope.row.classsId">未分配班级</span>
                        <span v-else>{{ getClassNameSync(scope.row.classsId) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作"
                    width="120">
                    <template #default="scope">
                        <el-button size="small"
                            type="primary"
                            @click="openEditDialog(scope.row)">
                            <el-icon>
                                <edit />
                            </el-icon></el-button>
                        <el-button size="small"
                            type="danger"
                            @click="handleDelete(scope.row.studentId)">
                            <el-icon>
                                <delete />
                            </el-icon></el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="pageNum"
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 添加学生对话框 -->
        <el-dialog v-model="addDialogVisible"
            title="添加学生"
            width="500px"
            :before-close="handleAddDialogClose">
            <el-form ref="addFormRef"
                :model="addForm"
                :rules="addRules"
                label-width="80px">
                <el-form-item label="学生姓名"
                    prop="studentName">
                    <el-input v-model="addForm.studentName"
                        placeholder="请输入学生姓名" />
                </el-form-item>
                <el-form-item label="学生ID"
                    prop="studentId">
                    <el-input v-model="addForm.studentId"
                        placeholder="请输入学生ID" />
                </el-form-item>
                <el-form-item label="性别"
                    prop="gender">
                    <el-radio-group v-model="addForm.gender">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="联系电话"
                    prop="studentPhone">
                    <el-input v-model="addForm.studentPhone"
                        placeholder="请输入联系电话" />
                </el-form-item>
                <el-form-item label="班级"
                    prop="classsId">
                    <el-select v-model="addForm.classsId"
                        placeholder="请选择班级"
                        filterable
                        :remote-method="remoteSearchClass"
                        :loading="classLoading"
                        remote
                        clearable>
                        <el-option label="未分配班级"
                            value="" />
                        <el-option v-for="item in filteredClasses"
                            :key="item.classsId"
                            :label="item.classsName"
                            :value="item.classsId" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取消</el-button>
                    <el-button type="primary"
                        @click="handleAddStudent">保存</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 编辑学生对话框（复用添加对话框，通过状态区分） -->
        <el-dialog v-model="editDialogVisible"
            title="编辑学生"
            width="500px"
            :before-close="handleAddDialogClose">
            <el-form ref="editFormRef"
                :model="editForm"
                :rules="addRules"
                label-width="80px">
                <el-form-item label="学生姓名"
                    prop="studentName">
                    <el-input v-model="editForm.studentName"
                        placeholder="请输入学生姓名" />
                </el-form-item>
                <el-form-item label="学生ID"
                    prop="studentId">
                    <el-input v-model="editForm.studentId"
                        placeholder="请输入学生ID"
                        disabled />
                </el-form-item>
                <el-form-item label="性别"
                    prop="gender">
                    <el-radio-group v-model="editForm.gender">
                        <el-radio :label="1">男</el-radio>
                        <el-radio :label="0">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="联系电话"
                    prop="studentPhone">
                    <el-input v-model="editForm.studentPhone"
                        placeholder="请输入联系电话" />
                </el-form-item>
                <el-form-item label="班级"
                    prop="classsId">
                    <el-select v-model="editForm.classsId"
                        placeholder="请选择班级"
                        filterable
                        :remote-method="remoteSearchClass"
                        :loading="classLoading"
                        remote
                        clearable>
                        <el-option label="未分配班级"
                            value="" />
                        <el-option v-for="item in filteredClasses"
                            :key="item.classsId"
                            :label="item.classsName"
                            :value="item.classsId" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleeditDialogClose">取消</el-button>
                    <el-button type="primary"
                        @click="handleEditStudent">保存修改</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import {
    getStudentList,
    deleteStudent,
    addStudent,
    updateStudent,
    getStudentById
} from '@/api/student'
import {
    getClasssList,
    getClasssDetail
} from '@/api/classs'
import { ElMessageBox, ElMessage, ElNotification } from 'element-plus'

export default {
    name: "Student",
    data() {
        return {
            loading: false,
            classLoading: false,
            multipleSelection: [],
            searchForm: {
                studentId: '',
                studentName: '',
                classsId: ''
            },
            studentList: [],
            total: 0,
            pageNum: 1,
            pageSize: 10,
            orderBy: 'studentId',
            classes: [],
            filteredClasses: [],
            classMap: {},
            isClassDataLoaded: false,
            missingClassIds: new Set(),

            // 添加学生功能相关数据
            addDialogVisible: false,
            addForm: {
                studentName: '',
                studentId: '',
                gender: 1,
                studentPhone: '',
                classsId: ''
            },
            addFormRef: null,
            addRules: {
                studentName: [{ required: true, message: '请输入学生姓名', trigger: 'blur' }],
                // studentId: [{ required: true, message: '请输入学生ID', trigger: 'blur' }],
                studentPhone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }]
            },

            currentStudentId: null,  // 当前编辑的学生ID
            isEditMode: false,       // 是否为编辑模式

            // 添加学生功能相关数据（修改部分字段）
            editDialogVisible: false,
            editForm: {
                studentName: '',
                studentId: '',
                gender: 1,
                studentPhone: '',
                classsId: ''
            },
        }
    },
    mounted() {
        Promise.all([
            this.fetchStudentList(),
            this.fetchClassList()
        ]).then(() => {
            this.checkClassMapping()
        }).catch(error => {
            console.error('初始化加载失败:', error)
            ElMessage.error('初始化加载失败，请刷新页面重试')
        })
    },
    methods: {
        // 从API获取班级列表
        async fetchClassList() {
            this.classLoading = true
            try {
                const response = await getClasssList(1, 1000, 'classsId', {})
                if (response.code === 200) {
                    const classData = response.data.list || response.data || []
                    this.classes = classData
                    this.filteredClasses = [...classData]
                    this.buildClassMap()
                    this.isClassDataLoaded = true
                } else {
                    ElMessage.error(response.msg || '获取班级列表失败')
                }
            } catch (error) {
                console.error('获取班级列表错误:', error)
                ElMessage.error('获取班级列表失败')
            } finally {
                this.classLoading = false
            }
        },

        // 构建班级ID到名称的映射表
        buildClassMap() {
            this.classMap = {}
            this.classes.forEach(cls => {
                const classId = String(cls.classsId).trim()
                this.classMap[classId] = cls.classsName
            })
        },

        // 同步获取班级名称（用于模板渲染）
        getClassNameSync(classsId) {
            if (!classsId) return '未分配班级'

            const classId = String(classsId).trim()

            // 先从映射表获取
            if (this.classMap[classId]) {
                return this.classMap[classId]
            }

            return `班级不存在 (ID: ${classId})`
        },

        // 检查班级映射关系
        checkClassMapping() {
            if (this.studentList.length && this.isClassDataLoaded) {
                const missingIds = new Set()

                this.studentList.forEach(student => {
                    const classId = String(student.classsId).trim()
                    if (!this.classMap[classId]) {
                        missingIds.add(classId)
                    }
                })

                if (missingIds.size > 0) {
                    console.log('缺失的班级ID列表:', Array.from(missingIds))
                }
            }
        },

        async fetchStudentList() {
            this.loading = true
            try {
                const response = await getStudentList(this.pageNum, this.pageSize, this.orderBy, this.searchForm)
                if (response.code === 200) {
                    this.studentList = response.data.list || []
                    this.total = response.data.total || 0
                } else {
                    ElMessage.error(response.msg || '获取学生列表失败')
                }
            } catch (error) {
                console.error('获取学生列表错误:', error)
                ElMessage.error('获取学生列表失败')
            } finally {
                this.loading = false
            }
        },

        handleSearch() {
            this.pageNum = 1
            this.fetchStudentList()
        },

        handleReset() {
            this.searchForm = {
                studentId: '',
                studentName: '',
                classsId: ''
            }
            this.fetchStudentList()
        },

        async handleDelete(studentId) {
            await ElMessageBox.confirm(
                `确定要删除学生 "${studentId}" 吗?`,
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).then(async () => {
                const response = await deleteStudent(studentId)
                if (response.code === 200) {
                    ElMessage.success('删除学生成功')
                    this.fetchStudentList()
                } else {
                    ElMessage.error(response.msg || '删除学生失败')
                }
            }).catch(() => {
                // 取消删除
            })
        },

        formatGender(gender) {
            return gender === 1 ? '男' : '女'
        },

        remoteSearchClass(query) {
            if (!query) {
                this.filteredClasses = [...this.classes]
                this.classLoading = false
                return
            }

            this.classLoading = true
            setTimeout(() => {
                this.filteredClasses = this.classes.filter(cls =>
                    cls.classsName.toLowerCase().includes(query.toLowerCase()) ||
                    cls.classsId.includes(query)
                )
                this.classLoading = false
            }, 300)
        },

        handleSizeChange(val) {
            this.pageSize = val
            this.fetchStudentList()
        },

        handleCurrentChange(val) {
            this.pageNum = val
            this.fetchStudentList()
        },

        handleSelectionChange(val) {
            this.multipleSelection = val
        },

        // 打开添加学生对话框
        openAddDialog() {
            this.addDialogVisible = true
            // 重置表单数据
            this.addForm = {
                studentName: '',
                studentId: '',
                gender: 1,
                studentPhone: '',
                classsId: ''
            }
            // 重置表单验证状态
            if (this.addFormRef) {
                this.addFormRef.resetFields()
            }
        },

        // 关闭添加学生对话框
        handleAddDialogClose(done) {
            if (this.addFormRef) {
                this.addFormRef.validate((valid) => {
                    if (valid) {
                        done()
                    } else {
                        // 表单未填写完毕，允许关闭
                        done()
                        return false
                    }
                })
            } else {
                done()
            }
        },

        // 处理添加学生
        async handleAddStudent() {
            // 安全检查表单引用
            if (!this.$refs || !this.$refs.addFormRef) {
                console.error('表单引用未找到', this.$refs)
                ElMessage.error('表单加载失败，请刷新页面重试')
                return
            }

            const formRef = this.$refs.addFormRef

            // 验证表单
            formRef.validate(async (valid) => {
                if (valid) {
                    try {
                        console.log('提交的学生数据:', this.addForm)
                        console.log('班级ID:', this.addForm.classsId)

                        // 调用添加学生API
                        const response = await addStudent(this.addForm.classsId, this.addForm)

                        if (response.code === 200) {
                            ElMessage.success('添加学生成功')
                            this.addDialogVisible = false
                            // 刷新学生列表
                            this.fetchStudentList()
                        } else {
                            ElMessage.error(response.msg || '添加学生失败')
                        }
                    } catch (error) {
                        console.error('添加学生错误:', error)
                        ElMessage.error('添加学生失败，请稍后重试')

                        // 开发环境显示详细错误
                        if (process.env.NODE_ENV !== 'production') {
                            ElNotification({
                                title: '错误详情',
                                message: error.message || JSON.stringify(error),
                                type: 'error',
                                duration: 0
                            })
                        }
                    }
                } else {
                    console.log('表单验证失败')
                    ElMessage.warning('请检查并填写必填字段')
                    return false
                }
            })
        },
        // 打开编辑学生对话框
        async openEditDialog(student) {
            this.isEditMode = true
            this.editDialogVisible = true
            this.currentStudentId = student.studentId

            try {
                // 获取学生详情
                const response = await getStudentById(student.studentId)
                if (response.code === 200) {
                    const studentData = response.data
                    // 填充表单数据
                    this.editForm = {
                        studentName: studentData.studentName,
                        studentId: studentData.studentId,
                        gender: studentData.gender || 1,
                        studentPhone: studentData.studentPhone || '',
                        classsId: studentData.classsId || ''
                    }
                } else {
                    ElMessage.error(response.msg || '获取学生详情失败')
                    this.editDialogVisible = false
                }
            } catch (error) {
                console.error('获取学生详情错误:', error)
                ElMessage.error('获取学生详情失败，请稍后重试')
                this.editDialogVisible = false
            }
        },

        // 处理编辑学生
        async handleEditStudent() {
            // 安全检查表单引用
            if (!this.$refs || !this.$refs.editFormRef) {
                console.error('表单引用未找到', this.$refs)
                ElMessage.error('表单加载失败，请刷新页面重试')
                return
            }

            const formRef = this.$refs.editFormRef

            // 验证表单
            formRef.validate(async (valid) => {
                if (valid) {
                    try {
                        console.log('编辑的学生数据:', this.editForm)

                        // 构建更新数据
                        const updateData = {
                            ...this.editForm,
                            studentId: this.editForm.studentId // 确保ID正确
                        }

                        // 调用更新学生API
                        const response = await updateStudent(updateData)

                        if (response.code === 200) {
                            ElMessage.success('更新学生成功')
                            this.editDialogVisible = false
                            this.isEditMode = false
                            // 刷新学生列表
                            this.fetchStudentList()
                        } else {
                            ElMessage.error(response.msg || '更新学生失败')
                        }
                    } catch (error) {
                        console.error('更新学生错误:', error)
                        ElMessage.error('更新学生失败，请稍后重试')
                    }
                } else {
                    console.log('表单验证失败')
                    ElMessage.warning('请检查并填写必填字段')
                    return false
                }
            })
        },

        // 关闭对话框时重置状态
        handleeditDialogClose(done) {
            if (typeof done !== 'function') {
                // 如果done不是函数（例如直接点击取消按钮），直接关闭对话框
                this.editDialogVisible = false;
                return;
            }
            if (this.editFormRef) {
                this.editFormRef.validate((valid) => {
                    if (valid || !this.isEditMode) {
                        // 编辑模式下不重置表单，添加模式下重置
                        if (!this.isEditMode) {
                            this.editForm = {
                                studentName: '',
                                studentId: '',
                                gender: 1,
                                studentPhone: '',
                                classsId: ''
                            }
                        }
                        done();
                    } else {
                        done()
                        return false
                    }
                })
            } else {
                done()
            }
        },
    }
}
</script>

<style scoped>
.student-page {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-form {
    margin-bottom: 15px;
}

.pagination {
    margin-top: 20px;
    text-align: right;
}

.search-form .el-form-item {
    margin-bottom: 0;
}

.search-form .el-input,
.search-form .el-select {
    width: 100%;
}

.search-form .el-button {
    margin-right: 5px;
}
.right-align-col {
    display: flex;
    justify-content: flex-end;
    align-items: center;
}
</style>